<template>
  <el-card>
    <!-- 查询条件开始 -->
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="菜单名称" prop="menuName">
        <el-input
            v-model="queryParams.menuName"
            placeholder="请输入菜单名称"
            clearable
            size="small"
            style="width:240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            size="small"
            style="width:200px"
        >
          <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="normal" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="danger" icon="el-icon-plus" size="mini" @click="handleAdd">添加</el-button>
      </el-form-item>
    </el-form>
    <!-- 查询条件结束 -->
    <!-- 数据表格开始 -->
    <el-table
        border
        :data="menuTableList"
        row-key="menuId"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="菜单名称" align="left" prop="menuName"/>
      <el-table-column label="菜单类型" align="center" prop="menuType">
        <template slot-scope="scope">
          <el-tag
              :type="scope.row.menuType==='M'?'primary':scope.row.menuType==='C'?'danger':'success'"
          >
            {{ scope.row.menuType === 'M' ? '目录' : scope.row.menuType === 'C' ? '菜单' : '权限' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="组件路径" align="center" prop="path"/>
      <el-table-column label="权限标识" align="center" prop="percode"/>
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormatter"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180px" />
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" size="mini" @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button v-if="scope.row.menuType === 'M'" type="text" icon="el-icon-plus" size="mini"
                     @click="handleAdd(scope.row)">添加
          </el-button>
          <el-button type="text" icon="el-icon-delete" size="mini" @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>

    </el-table>
    <!-- 数据表格结束 -->

    <!-- 添加和修改的弹出层开始 -->
    <el-dialog
        :title="title"
        :visible.sync="open"
        width="600px"
        center
        append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-row>
          <el-col :span="24">
            <el-form-item label="上级菜单" prop="parentName">
              <treeselect
                  v-if="form.status === 1"
                  v-model="form.parentName"
                  :show-count="true"
                  :default-expand-level="1"
                  :normalizer="normalizer"
                  :disabled="form.path!=null"
              />
              <el-input v-else value="主目录" disabled></el-input>
              <el-input v-else v-model="form.parentId" style="display: none"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单类型" prop="menuType">
              <el-radio-group v-model="form.menuType" disabled>
                <el-radio label="M">目录</el-radio>
                <el-radio label="C">菜单</el-radio>
                <!--                                    <el-radio label="F">按钮</el-radio>-->
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="menuName">
              <el-input v-model="form.menuName" placeholder="请输入菜单名称" clearable size="small"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="路由地址" prop="path">
              <el-input v-model="form.path" placeholder="请按照格式输入" clearable size="small"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.menuType==='F'" label="权限标识" prop="percode">
              <el-input v-model="form.percode" placeholder="请输入权限标识" clearable size="small"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                    v-for="dict in statusOptions"
                    :key="dict.dictValue"
                    :label="dict.dictValue"
                    :value="dict.dictValue"
                >{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 添加和修改的弹出层结束 -->

  </el-card>
</template>


<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  components: {
    Treeselect
  },
  data(){
    return {
      // 菜单表的数据
      menuTableList: [],
      // 菜单树的数据
      menuOptions: [],

      // 弹出层的title
      title: '',
      // 是否打开弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        menuName: undefined,
        status: undefined,
      },
      // 表单数据
      form: {
        menuId: undefined,
        statuss: 0,  // 0代表点击添加目录，1代表添加字菜单
        menuType: 'M',
        menuName: undefined,
        parentId: 0,
        parentName: undefined,
        path: undefined,
      },
      // 表单校验
      rules: {
        menuName: [
          {required: true, message: '菜单名称不能为空', tirgger: 'blur'}
        ],
        path: [
          {required: true, message: '路由路径不能为空', tirgger: 'blur'}
        ]
      }
    }
  },
  created() {
    // 查询表格数据
    this.getMenuList();
    this.loadStatus();
  },
  methods: {
    // 查询表格数据
    getMenuList() {
      this.$http.post("/system/menu/listAll",this.queryParams).then(resp=>{
        console.log(resp.data)
        if(resp.data.code===200){
          this.menuTableList=this.handleTree(resp.data.data,"menuId")
        }
      })
    },
    // 添加
    handleAdd(row) {
      this.title = '---添加菜单---'
      this.reset()
      this.getTreeselect()
      if (row != null) {
        this.form.parentId = row.menuId
        this.form.menuName = row.menuName
        this.form.parentName = row.menuName
        console.log(this.form.parentId)
        console.log(this.form.parentName)
        if (row.menuType == 'M') {
          this.form.menuType = 'C'
        } else if (row.menuType == 'C') {
          this.form.menuType = 'F'
        }
      }
      this.form.statuss = 0

      if (row.menuId != null) {
        this.form.statuss = 1
      }
      this.form.path = row.path
      this.open = true
    },
    // 打开修改弹窗并数据回显
    handleUpdate(row) {
      this.title = '---修改菜单---'
      this.open = true
      this.getTreeselect()
      this.$http.get("/system/menu/getByMenuId/"+row.menuId).then(res=>{
        console.log("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
        console.log(res)
        this.form = res.data.data
      })
    },
    // 查询菜单下拉树的数据
    getTreeselect() {
      this.$http.post("/system/menu/listAll",this.queryParams).then(res=>{
        // console.log(res.data.data)
        this.menuOptions = []
        const menu = {menuId: 0, menuName: '主类目', children: []}
        menu.children = this.handleTree(res.data, 'menuId')
        for (const rowKey of menu.children) {
          rowKey.children = []
        }
        this.menuOptions.push(menu)
      })
    },
    handleTree(data, id, parentId, children, rootId){
      id = id || 'id'
      parentId = parentId || 'parentId'
      children = children || 'children'
      rootId = rootId || 0
      // 对源数据进行深度克隆
      if (!Array.isArray(data)) return []
      const cloneData = JSON.parse(JSON.stringify(data))||[]
      // 循环所有的项目
      const treeData = cloneData.filter(father => {
        const branchArr = cloneData.filter(child => {
          return father[id] === child[parentId]
        })
        branchArr.length > 0 ? father.children = branchArr : ''
        // 返回上一层
        return father[parentId] === rootId
      })
      return treeData !== '' ? treeData : data
    },
    // 自定义键名
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.menuId,
        label: node.menuName,
        children: node.children
      }
    },
    // 提交
    handleSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          // 做添加
          if (this.form.menuId === undefined) {
            if (this.form.statuss === 0) {
              this.form.parentId = 0
            }
            this.$http.post("/system/menu/add_update_menu",this.form).then(res=>{
              this.$message.success('添加成功')
              this.getMenuList()// 列表重新查询
              location.reload()
              this.open = false// 关闭弹出层
            })
          } else { // 做修改
            this.$http.post("/system/menu/add_update_menu",this.form).then(res=>{
              this.$message.success('修改成功')
              this.getMenuList()// 列表重新查询
              location.reload()  // 重新加载所有页面资源
              this.open = false// 关闭弹出层
            })
          }
        }
      })
    },
    // 取消
    cancel() {
      this.resetForm()
      this.open = false
      this.title = ''
    },
    resetForm() {
      this.$refs.queryForm.resetFields()
    },
    reset() {
      this.resetForm('form')
      this.form = {
        menuId: undefined,
        statuss: 0,
        menuType: 'M',
        menuName: undefined,
        parentId: 0,
        parentName: undefined,
        path: undefined,
      }

    },
    resetQuery() {
      this.queryParams={
        menuName: undefined,
        status:undefined,
        pageNum: 1,
        pageSize: 5
      }
      this.getMenuList();
    },

    //加载状态
    loadStatus() {
      this.$http.get("/system/dict/data/type/sys_normal_disable").then(resp=>{
        this.statusOptions=resp.data.data;
      })
    },
    // 分页pageSize变化时触发
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getMenuList()
    },
    // 点击上一页  下一页，跳转到哪一页面时触发
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getMenuList()
    },
    // 格式化状态
    statusFormatter(row){
      let statusName="未知";
      this.statusOptions.filter(item=>{
        if(row.status===item.dictValue){
          statusName=item.dictLabel;
        }
      })
      return statusName;
    },
    // 删除
    handleDelete(row) {
      const menuId = row.menuId
      console.log(menuId)
      this.$confirm('此操作将永久删除该菜单权限数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        this.$http.delete("/system/menu/deleteByMenuId/"+menuId).then(res=>{
          this.$message.success('删除成功')
          location.reload()
          this.getMenuList()// 全查询
        })
      }).catch(() => {
        this.$message.warning('取消删除')
      })
    },

    // 搜索
    handleQuery(){
      this.getMenuList();
    },
  }

}
</script>

<style scoped>

</style>